package com.lc.dubbox.consumer;

import com.lc.dubbox.api.UserService;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ImportResource;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;

/**
 * Created by lichao on 18/1/28.
 */
//@SpringBootApplication
@ImportResource(locations={"classpath:dubbox-consumer.xml"})
public class ConsumerApplication {

    public static void main(String[] args) {

        final String port = "8888";
        //final String port = "7777";

        //测试Rest服务
        getUser("http://localhost:" + port + "/api/users/1.json");
        getUser("http://localhost:" + port + "/api/users/1.xml");
        System.exit(0);
        //测试常规服务
        ConfigurableApplicationContext context = SpringApplication.run(ConsumerApplication.class, args);
        context.start();
        UserService userService = context.getBean(UserService.class);
        System.out.println(userService.getUser(1L));
    }


    private static void getUser(String url){
        System.out.println("Getting user url" + url);
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(url);
        Response response = target.request().get();
        try {
            if (response.getStatus() != 200) {
                throw new RuntimeException("Failed with HTTP error code : " + response.getStatus());
            }
            System.out.println("Successfully got result: " + response.readEntity(String.class));
        } finally {
            response.close();
            client.close();
        }
    }
}
